/**
 * 类名：MSOffice
 * 创建日期： 2014-10-25 下午12:01:21
 * 
 */
package com.erms.util.office;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import com.erms.util.LogUtil;
import com.erms.util.StringUtil;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.w3c.dom.Document;

/**
 * @author hmb
 *         备注：
 * 
 */
public abstract class MSOffice {
	protected Logger			logger			= LogUtil.getLogger(getClass());

	final public static String	defaultEncoding	= "utf-8";

	// TODO 这里需要更改存储office转换文件的根目录
	protected static String		rootPath		= ServletActionContext
														.getServletContext()
														.getRealPath("/temp");
	// protected static String rootPath = "d:/test/";

	protected String			inputFile;

	protected String			outputFile;

	protected String			encoding;

	public String getRootPath() {

		return rootPath;
	}

	public void setEncoding(String encoding) {

		this.encoding = encoding == null ? defaultEncoding : encoding;
	}

	public void setRootPath(String rootPath) {

		this.rootPath = rootPath;
	}

	/**
	 * 
	 */
	public MSOffice(String inputFileName) {

		this(inputFileName, defaultEncoding);
	}

	/**
	 * 
	 */
	public MSOffice(String inputFileName, String encoding) {

		logger.debug("当前office文档为：" + inputFileName);
		this.inputFile = inputFileName;
		setEncoding(encoding);
	}

	/**
	 * 保存为html，如果指定了输出文件路径则同时保存成文件
	 * 
	 * @param document 从office文档解析出来的document对象
	 * @return html字符串
	 * @throws Exception
	 */
	protected String saveAsHtml(Document document) throws Exception {

		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		StreamResult streamResult = new StreamResult(outputStream);
		DOMSource domSource = new DOMSource(document);
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer serializer = tf.newTransformer();
		serializer.setOutputProperty(OutputKeys.ENCODING, encoding);
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		serializer.setOutputProperty(OutputKeys.METHOD, "html");
		serializer.transform(domSource, streamResult);

		String html = outputStream.toString(encoding);
		if (this.outputFile != null) {
			// TODO 这里需要修改生成html文件的路径生成规则
			FileWriter writer = new FileWriter(rootPath + this.outputFile);
			writer.write(html);
			writer.close();
		}
		outputStream.close();
		return html;
	}

	protected boolean isTrueType(String fontName) {

		if (StringUtil.isNull(fontName)) { return false; }
		String[] trueType = new String[]{"Tahoma", "Times New Roman",
				"Calibri", "Arial"};
		for (String type : trueType) {
			if (fontName.contains(type)) return true;
		}
		return false;
	}

	protected String getFileName() {

		String name = "";
		int a = this.inputFile.lastIndexOf("/");
		int b = this.inputFile.lastIndexOf(".");
		if (a > 0 && b > 0) {
			name = inputFile.substring(a+1, b);
		} else {
			name = StringUtil.random(10);
		}

		logger.debug("文件名：" + name);
		return StringUtil.urlEncode(name);
	}

	protected String readSavedInfo(String path) {

		File file = new File(path + "info.json");

		StringBuilder sb = new StringBuilder();
		try {
			InputStreamReader reader = new InputStreamReader(
					new FileInputStream(file), "utf-8");
			BufferedReader br = new BufferedReader(reader);
			String temp = null;
			while ((temp = br.readLine()) != null) {
				sb.append(temp);
			}
			br.close();
			return sb.toString();
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			logger.error("readSavedInfo + FileNotFoundException", e);
		}
		return null;
	}

	protected void saveInfo(String path, String json) {

		try {
			File file = new File(path + "info.json");
			if (!file.exists()) {
				file.createNewFile();
			}
			OutputStreamWriter writer = new OutputStreamWriter(
					new FileOutputStream(file), "utf-8");
			writer.write(json);
			writer.close();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			logger.error("saveInfo + IOException", e);
		}

	}
}
